Ext.BLANK_IMAGE_URL = 'js/ext/resources/images/default/s.gif';
Ext.Ajax.timeout = 90000;
Ext.data.Connection.timeout=60000;
var Obj = {};
var ddl={};
var continue_session = false;
var delItem = new Ext.menu.Item({id:'delete-node',text:'Usuń',iconCls:'delete-icon'});
var createItem = new Ext.menu.Item({id:'create-node',text:'Utwórz',iconCls:'db-object-icon'});
var refreshItem = new Ext.menu.Item({id:'refresh-node',text:'Odśwież',iconCls:'db-refresh-icon'});
var ddlItem = new Ext.menu.Item({id:'ddl-node',text:'Pokaż DDL',iconCls:'ddl-icon'});
var nodeMenu = new Ext.menu.Menu({items: [ddlItem],
listeners: {
    itemclick: function(item) {
        switch (item.id) {
            case 'delete-node':
                var n = item.parentMenu.contextNode;
                if (n.parentNode) {
                	Msg('Node,depth:'+n.getDepth(), item.text+':'+ n.text); 
                    //n.remove();
                }
                break;
			case 'ddl-node':
				 var n = item.parentMenu.contextNode;
				 dll(n);
        }
    }
}
});
var folderMenu = new Ext.menu.Menu({
    items: [refreshItem,createItem],
listeners: {
    itemclick: function(item) {
        switch (item.id) {
            case 'refresh-node':var n = item.parentMenu.contextNode;n.reload();break;
            case 'create-node':
                var n = item.parentMenu.contextNode;
                if (n.parentNode && Obj.subtype[n.attributes.t]) {
                	Ext.getCmp('main-body').loadObject(Obj.subtype[n.attributes.t],'file-txt');
                }
            	break;
        }
    }
}
});
ApiPanel = function(config) {
	var conf = config||{id:'api-tree',iconCls:'database-icon',title:'',rootVisible:true};
    ApiPanel.superclass.constructor.call(this, {
        id: conf.id,
        iconCls:conf.iconCls,
        title: conf.title,
        split:true,
        width: 280,
        minSize: 175,
        maxSize: 500,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        rootVisible:conf.rootVisible,
        lines:false,
        autoScroll:true,
        animCollapse:false,
        animate: false,
        collapseMode:'mini',
        loader: new Ext.tree.TreeLoader({preloadChildren: true,clearOnLoad: true,dataUrl: 'tree.jsp'}),
        root: new Ext.tree.AsyncTreeNode({text:'root',id:'root',expanded:false}),
        collapseFirst:false,
        listeners: {
            contextmenu: function(node, e) {
                node.select();
                var c = node.getOwnerTree().contextMenu;
                var menu = {};
                if(node.isLeaf()){
                	menu = nodeMenu;
                }else{
                	menu = folderMenu;
                }
                c = menu;
                c.contextNode = node;
                c.showAt(e.getXY());
            }//,
    	},
    	tbar:new Ext.Toolbar({})
    });
};
Ext.extend(ApiPanel, Ext.tree.TreePanel);
var ObjPanel = Ext.extend(Ext.Panel, {//Ext.TabPanel, {
    closable: true,
    autoScroll:true,
    layout:'fit',
    initComponent : function(){
        ObjPanel.superclass.initComponent.call(this);
    }
});
MainPanel = function(){
    MainPanel.superclass.constructor.call(this, {
        id:'main-body',
        region:'center',
        margins:'0 5 5 0',
        resizeTabs: true,
        animScroll:false,
        minTabWidth: 135,
        tabWidth: 135,
        plugins: [new Ext.ux.TabCloseMenu(),new Ext.ux.TabScrollerMenu({maxText:10,pageSize:5})],
        enableTabScroll: true,
        activeTab: 0,
		defaults:{
    		autoScroll: true,
    		xtype:'panel',
    		bodyStyle : 'padding:20px',
    		closable:true,animScroll:false,layout:'fit'
    	},
        items:[ {
            id:'info-panel',
            title: 'Oracle',
            autoLoad: {url: 'info.jsp',scripts: true, scope: this,method:'POST'},
            iconCls:'oracle-icon',
			xtype:'panel',
			bodyStyle : '',
			closable:false
        }
		]
    });
};
Ext.extend(MainPanel, Ext.TabPanel, {
    initEvents : function(){
        MainPanel.superclass.initEvents.call(this);
        this.body.on('click', this.onClick, this);
    },
    loadObject : function(type,icon){
        var id = 'object-' + type+'-new';
        	var op = Obj.panels[type];
        	if(!op){
        		Msg('Brak definicji obiektu','Dla wezla o numerze:'+type);return;
        	}
            var p = this.add(new ObjPanel({
                id: id,
                title:'Nowy obiekt',
                iconCls: icon,
                defaults:{autoScroll: true},
                autoLoad:Ext.decode(String.format(op.toString(),null,null))
            }));
            var w = new Ext.Window(
            		{
            			id:'create-window',
            			title:'Nowy obiekt..',
            			collapsible : false,
            			constrain : true,
            			plain : true,
						modal : true,
						maximizable : true,
						layout : 'fit',
						height : 530,
						width : 1000,
            			items:p
            		}
            );
            w.show();
    },    
	loadObjectFromNode : function(node){
    	var atrs = node.attributes, t = atrs.t, schema = atrs.schema,text = node.text;
        var id = 'object-' + t+'-'+text;
        var tab = this.getComponent(id);
        if(tab){
            this.setActiveTab(tab);
        }else{
        	var op = Obj.panels[t];
        	if(!op){
        		Msg('Brak definicji obiektu','Dla węzła o numerze:'+t+' z nazwą:'+text);return;
        	}
        	var obj_title = text;
        	if(schema){
        		obj_title = schema+':'+obj_title;
        	}
			var panel = new ObjPanel({
                id: id,
                title : obj_title,
                iconCls: atrs.iconCls,
				defaults:{autoScroll: true,layout:'ux.center'},layout:'fit',
				autoLoad: Ext.decode(String.format(op.toString(),schema,text))
            });
            var p = this.add(panel);
            this.setActiveTab(p);
        }
    },
    checkTabIcon: function(node){
    	alert('zaladowano:'+node.text);
    }
});
LoginHide = function(){
	return new Ext.Action({text:'',itemId:'actionHide',
		handler:function(data){
			Ext.getCmp('hd').show();
			var api=Ext.getCmp('api-tree');			api.show();
			var sec=Ext.getCmp('sec-tree');			sec.show();
			var mb=Ext.getCmp('main-body');			mb.show();
			var acc = Ext.getCmp('tp');				acc.show();
			LoginPanel.hide();
			if(data){
				var data_schema = data.schema;
			    var com = combo({id:'combo_schema',emptyText:data_schema,fieldLabel:'Wybierz schemat'});
				com.on('select',function(combo,record,index){
					var schema = data_schema;
					if(record!=null){
						schema = record ? record.get(combo.displayField) : combo.valueNotFoundText;
					}
					var root = api.getRootNode();
					root.attributes.schema=schema;
					root.reload();
				});
				api.getTopToolbar().removeAll();
				api.getTopToolbar().add(['Schemat:',com,{iconCls: 'icon-expand-all',tooltip: 'Rozwiń wszystkie',
	            	handler: function(){ api.root.expand(true); }},'-',{iconCls: 'icon-collapse-all',tooltip: 'Zwiń wszystkie',
	                handler: function(){ api.root.collapse(true); }
	            }]);
			    api.getLoader().on("beforeload",function(self, node){
			    	var root = api.getRootNode();
			    	var path = root.getPath("text");
			    	var schema = root.attributes.schema;
			    	var natrs = node.attributes,t = natrs.t;
			    	if(schema==null){
			    		schema = data_schema;
			    	}
			    	if(node.text=='root'){
			    		path = "root/"+schema;
			    	}else{
			    		path = t;
			    	}
			    	this.baseParams={'path':path,'cmd':'get','schema':schema};
					this.baseAttrs={'schema':schema,'qtip':t};
			    }	);
			    sec.getLoader().on("beforeload",function(self, node){
			    	var root = sec.getRootNode();
			    	var path = root.getPath("text");
			    	if(node.text=='root'){
			    		path = "root/";
			    	}else{
			    		path = t;
			    	}
			    	this.baseParams={'path':path,'cmd':'getSec'};
					this.baseAttrs={'qtip':t};
			    }	);
				com.doQuery('',true);
				com.setValue(data_schema,true);
				api.getRootNode().attributes.schema=data_schema;
				api.expandPath('/root/'+data_schema);
				api.setTitle(data.hostname+':'+data.sid);
				sec.getRootNode().attributes.schema=data_schema;
				sec.expandPath('/root/');
				Ext.getCmp('v').doLayout();acc.doLayout();
			}
		}   	
	});
};
LoginShow = function (){
	return new Ext.Action({text:'',itemId:'actionShow',
		handler:function(){
				Ext.getCmp('hd').hide();
				Ext.getCmp('tp').hide();
//				Ext.getCmp('api-tree').hide();
//				Ext.getCmp('sec-tree').hide();
				Ext.getCmp('main-body').hide();
				LoginPanel.show();
		}
	});
};
Ext.onReady(function(){
    Ext.QuickTips.init();
    var api = new ApiPanel();
    var sec = new ApiPanel({id:'sec-tree',title:'Użytkownicy',iconCls:'users-icon',rootVisible:true});
    var mainPanel = new MainPanel();
    api.on('click', function(node, e){
         if(node.isLeaf()){
            e.stopEvent();
            mainPanel.loadObjectFromNode(node);
         }
    });
    sec.on('click', function(node, e){
        if(node.isLeaf()){
           e.stopEvent();
           mainPanel.loadObjectFromNode(node);
        }
    });
    var tp = new Ext.Panel({layout:'accordion',//TabPanel({
        region:'west',
        split:true,
        lines:false,
        width: 280,
        minSize: 175,
        maxSize: 500,
        collapsible: true,
        margins:'0 0 5 5',
        cmargins:'0 0 0 0',
        autoScroll:true,
        animCollapse:false,
        collapseMode:'mini',
        animate: false,
        //collapseFirst:false,
    	id:'tp',
    	activeTab: 0,
    	tabPosition:'bottom',
    	items:[api,sec]
    });
    
    var actionLoginShow = LoginShow();
    var actionLoginHide =LoginHide();
    var hd = new Ext.Panel({id:'hd',border: false,layout:'anchor',region:'north',cls: 'docs-header',height:60,
        items: [{xtype:'box',el:'header',border:false,anchor: 'none -25'},
	        new Ext.Toolbar({
	            cls:'top-toolbar',
	            items:[{
    					text:'Plik',
    					shadow:true,
    					iconCls:'bmenu',
    					menu:[{text:'Zakończ',handler: function(){Ext.Ajax.request({url:'login/session.jsp',params:{action:'logout'},waitTitle:'Kończenie',waitMsg:'Trwa wylogowywanie...',success:function(){actionLoginShow.execute();}});}}]
    			  },'-',{
    				  	text:'Obiekt',
    				  	iconCls:'icon-cmp',
    				  	shadow:true,
    				  	menu:[
    				  	      {
    				  	    	  text:'Utwórz',
    				  	    	  iconCls:'forms-category-icon',
    				  	    	  menu:[
	    				  	      {text:'Funkcja',iconCls:'icon-method',handler: function(){   mainPanel.loadObject('49','icon-method'); }},
								  {text:'Indeks',iconCls:'index-icon',handler: function(){   mainPanel.loadObject('1541','index-icon'); }},
	    				  	      {text:'Pakiet',iconCls:'package-icon',handler: function(){   mainPanel.loadObject('50','package-icon'); }},
	    				  	      {text:'Ciało pakietu',iconCls:'package-spec-icon',handler: function(){   mainPanel.loadObject('51','package-spec-icon'); }},
	    				  	      {text:'Procedura',iconCls:'procedure-icon',handler: function(){   mainPanel.loadObject('48','procedure-icon'); }},
	    				  	      {text:'Sekwencja',iconCls:'icon-prop',handler: function(){   mainPanel.loadObject('38','icon-prop'); }},
	    				  	      {text:'Tabela',iconCls:'table-icon',handler: function(){   mainPanel.loadObject('32','table-icon'); }},
	    				  	      {text:'Trigger',iconCls:'icon-event',handler: function(){   mainPanel.loadObject('37','icon-event'); }},
	    				  	      {text:'Użytkownik',iconCls:'user-icon',handler: function(){   mainPanel.loadObject('18','user-icon'); }},
	    				  	      {text:'Synonim',iconCls:'synonym-icon',handler: function(){ mainPanel.loadObject('80','synonym-icon'); }},
	    				  	      {text:'Widok',iconCls:'view-icon',handler: function(){   mainPanel.loadObject('39','view-icon'); }}]
    				  	      }
    				  	      ]
    			  },'-',{
  				  	text:'Ustawienia',
				  	iconCls:'silk-cog',
				  	shadow:true,
				  	handler: function(){   
    					form = new Ext.form.FormPanel({  
    						standardSubmit: true, // traditional submit  
    						url: 'settings.jsp',  
    						border:false,  
    						labelWidth: 80,  
    						defaults: {  
    							xtype:'textfield',  
    							width: 150  
    						},  
    						items:[  
    							{fieldLabel:'Title',name:'title', allowBlank:false},  
    							{xtype:'combo',fieldLabel:'Year',name:'year',triggerAction:'all',store:[2009,2008,2007,2006]},  
    							{xtype:'numberfield',fieldLabel:'Revenues',name:'revenues'},  
    							{xtype:'textarea',fieldLabel:'Comment',name:'comment'},  
    							{xtype:'checkbox',fieldLabel:'',labelSeparator:'',boxLabel:'Available',name:'available'}  
    						]
    					});  
		    			var w = new Ext.Window({
		    				title: 'Ustawienia',
		    				constrain:true,
		    				width:300,
		    				height:270,
		    				bodyStyle: 'padding:10px;background-color:#fff;',
		    				buttons:[{
		    		        	text: 'Zapisz',
		    		        	handler: this.sendData
		    		    	},{
		    		        	text: 'Anuluj',
		    		        	handler: function(){
		    						w.close();
		    		        	}
		    		    	}],
		    				sendData: function(){
		    					form.getForm().submit();
		    				},
		    				items:form
		    			});
		    			w.show();
    				 }
			  }]
        })]
    });
    //Ext.Ajax.request({
    new Ext.data.Connection().request({
 	   url: 'login/session.jsp',
 	   success: function(result, option){
				obj = Ext.decode(result.responseText);
				if(obj.success){
					LoginHide().execute(obj.data);
				}else{
					actionLoginShow.execute();
				}
			},
			failure: function ( result, request) { 
				actionLoginShow.execute();
			},
			params: { action: 'check' }
    });
    var viewport = new Ext.Viewport({id:'v',layout:'border',items:[ hd, tp, mainPanel ]});
    //viewport.doLayout();
	Ext.getCmp('hd').hide();
	Ext.getCmp('tp').hide();
 	Ext.getCmp('api-tree').hide();
 	Ext.getCmp('sec-tree').hide();
	Ext.getCmp('main-body').hide();
});
